$(function() {
    $('#link-reg').on('click', function() {
        $('.login-a').hide();
        $('.reg-a').show();
    });
    $('#link-login').on('click', function() {
        $('.reg-a').hide();
        $('.login-a').show();
    });



    var form = layui.form;
    var layer = layui.layer;
    form.verify({
        pwd: [/^[\S]{6,12}$/, '密码长度应位于6-12位！'],
        repwd: function(value) {
            var pwd = $('.reg-a [name=password]').val();
            if (pwd != value) {
                return '两次密码不一致！请重新输入'
            }
        }
    });



    $('#reg-form').on('submit', function(e) {
        e.preventDefault();
        $.ajax({
            type: 'POST',
            url: '/api/reguser',
            data: {
                username: $('#reg-form [name=username]').val(),
                password: $('#reg-form [name=password]').val()
            },
            success: function(res) {
                if (res.status != 0) {
                    return layer.msg(res.message);
                } else {
                    layer.msg('注册成功！请登录');
                    $('#link-login').click();
                }
            }
        });

    });


    $('#login-form').on('submit', function(e) {
        e.preventDefault();
        $.ajax({
            type: 'POST',
            url: '/api/login',
            data: $(this).serialize(),
            success: function(res) {
                if (res.status != 0) {
                    return layer.msg('登陆失败！');
                } else {
                    layer.msg('登陆成功!');
                    localStorage.setItem('token', res.token);
                    location.href = "/index.html";
                }
            }
        })
    })
})